package com.dabaozhan.modules.wx_app.controller;

import com.alibaba.fastjson.JSON;
import com.dabaozhan.common.exception.RRException;
import com.dabaozhan.common.utils.DateUtils;
import com.dabaozhan.common.utils.OmsPage;
import com.dabaozhan.common.utils.RandomUtils;
import com.dabaozhan.modules.wx_app.base.ResponseDto;
import com.dabaozhan.modules.wx_app.entity.PurchaseFormEntity;
import com.dabaozhan.modules.wx_app.entity.SiteOrderEntity;
import com.dabaozhan.modules.wx_app.entity.SiteOrderImgEntity;
import com.dabaozhan.modules.wx_app.entity.UserEntity;
import com.dabaozhan.modules.wx_app.enums.ResponseCodeEnum;
import com.dabaozhan.modules.wx_app.facade.OrderFacade;
import com.dabaozhan.modules.wx_app.service.PurchaseFormService;
import com.dabaozhan.modules.wx_app.service.SiteOrderImgService;
import com.dabaozhan.modules.wx_app.service.SiteOrderService;
import com.dabaozhan.modules.wx_app.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author houzhong
 * @date 2019-01-07 12:27
 *
 * 订单
 */

@Api(value = "打包站订单", description = "用户接口")
@RestController
@RequestMapping("/wx_app")
public class OrderController {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);

    /**订单*/
    @Autowired
    private SiteOrderService siteOrderService;

    @Autowired
    private OrderFacade orderFacade;

    @Autowired
    private SiteOrderImgService siteOrderImgService;

    @Autowired
    private PurchaseFormService purchaseFormService;

    @ApiOperation(value = "订单查询")
    @RequestMapping(value = "/findOrderUser")
    public String findOrderUser(SiteOrderEntity v,Integer page,Integer size) {
        ResponseDto<OmsPage<SiteOrderEntity>> responseDto = new ResponseDto<OmsPage<SiteOrderEntity>>();
        try {
            int tomeSection = v.getTimeSection();
            Map<String, Object> params = new HashMap<>();
            params.put("userId",v.getUserId());
            params.put("page",(page - 1) * size);
            params.put("size",size);
            params.put("orderStatus",v.getOrderStatus());
            params.put("orderType",v.getOrderType());
            params.put("beginTime",DateUtils.getBeginDate(tomeSection));
            params.put("endTime",DateUtils.getEndDate(tomeSection));
            OmsPage<SiteOrderEntity> pages = siteOrderService.findBySiteOrder(params);
            if (pages.getResult().size()>0) {
                for (SiteOrderEntity entity : pages.getResult()) {
                    List<SiteOrderImgEntity> list = siteOrderImgService.getSiteOrderImgEntity(entity.getId());
                    if(!CollectionUtils.isEmpty(list)){
                        entity.setPictureImgList(list);
                    }
                }
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                responseDto.setResult(pages);
            }else {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_400);
            }

        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("订单查询发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("订单查询发生异常:{}-返回结果:{}",JSON.toJSONString(v),JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "查询订单详情")
    @RequestMapping(value = "/findOrderId")
    public String findOrderId(String id){
        ResponseDto<SiteOrderEntity> responseDto = new ResponseDto<SiteOrderEntity>();
        try {
            SiteOrderEntity siteOrder = siteOrderService.findById(id);
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
            responseDto.setResult(siteOrder);
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("查询订单详情发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("查询订单详情发生异常:{}-返回结果:{}",JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "查看图片")
    @RequestMapping(value = "/getSiteOrderImg")
    public String getSiteOrderImg(String siteOrderId){
        ResponseDto<List<SiteOrderImgEntity>> responseDto = new ResponseDto<List<SiteOrderImgEntity>>();
        try {
            List<SiteOrderImgEntity> list = siteOrderImgService.getSiteOrderImgEntity(siteOrderId);
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
            responseDto.setResult(list);
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("查看图片发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("查看图片发生异常:{}-返回结果:{}",JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "验货定价订单新增")
    @RequestMapping(value = "/orderSave")
    public String orderSave(SiteOrderEntity v){
        ResponseDto<SiteOrderEntity> responseDto = new ResponseDto<SiteOrderEntity>();
        try {
            v.setOrderNumber(RandomUtils.random6());
            siteOrderService.saveSiteOrder(v);
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("验货定价订单新增发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("验货定价订单新增发生异常:{}-返回结果:{}",JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "订单支付")
    @RequestMapping(value = "/orderPay")
    public String orderPay(SiteOrderEntity v){
        ResponseDto<SiteOrderEntity> responseDto = new ResponseDto<SiteOrderEntity>();
        try {
            responseDto =  orderFacade.addOrderLog(v);
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("订单支付发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("订单支付发生异常:{}-返回结果:{}",JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "订单修改状态")
    @RequestMapping("/updateOrderStatus")
    public String updateOrderStatus(SiteOrderEntity v) {
        ResponseDto<SiteOrderEntity> responseDto = new ResponseDto<SiteOrderEntity>();
        try {
            int result = siteOrderService.updateSiteOrder(v);
            if (result > 0) {
                if ("6".equals(v.getOrderStatus())) {
                    /**设置为取消状态*/
                    SiteOrderEntity siteOrder = siteOrderService.findById(v.getId());
                    PurchaseFormEntity purchaseForm = purchaseFormService.getPurchaseFormId(siteOrder.getOrderNumber());
                    purchaseForm.setOrderStatus(v.getOrderStatus());
                    purchaseFormService.updatePurchaseForm(purchaseForm);
                }
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
            }else {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_107);
            }
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("订单修改状态发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("订单修改状态发生异常:{}-返回结果:{}",JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }


}
